#include "stdlib.h"
#include "stdio.h"
#include "h/queue.h"

static void copyToNode(Item, Node *);
static void copyToItem(Node *, Item *);

void InitializeQueue(Queue * pq)
{
    pq->head = NULL;
    pq->tail = NULL;
    pq->len = 0;
}

bool QueueIsFull(const Queue * pq)
{
    return pq->len == MAXQUEUE;
}

bool QueueIsEmpty(const Queue * pq)
{
    return pq->len == 0;
}

int QueueItemCount(const Queue * pq)
{
    return pq->len;
}

bool EnQueue(Item item, Queue * pq)
{
    Node * new;

    if (QueueIsFull(pq))
        return false;

    new = (Node *)malloc(sizeof(Node));
    if (NULL == new)
    {
        fprintf(stderr, "Unable to allocate memory!\n");
        exit(EXIT_FAILURE);
    }

    copyToNode(item, new);
    new->next = NULL;

    if (QueueIsEmpty(pq))
        pq->head = new;
    else
        pq->tail->next = new;

    pq->tail = new;
    ++pq->len;

    return true;
}

bool DeQueue(Item * item, Queue * pq)
{
    Node * prev;

    if (QueueIsEmpty(pq))
        return false;


    prev = pq->head;
    copyToItem(prev, item);

    if ((pq->head = pq->head->next) == NULL) {
        pq->tail  = NULL;
    }

    free(prev);

    --pq->len;

    return true;
}

void EmptyTheQueue(Queue * pq)
{
//    Node * next;
//    Node * curr = pq->head;
//    while (curr != NULL) {
//        next = curr->next;
//        free(curr);
//        curr = next;
//    }
//
//    pq->head = pq->tail = NULL;
//    pq->len = 0;

    Item it;
    while (DeQueue(&it, pq))
        ;
}

static void copyToNode(Item item, Node * pn)
{
    pn->item = item;
}

static void copyToItem(Node * pn, Item * pi)
{
    *pi = pn->item;
}
